<?php namespace app\api\controller;

use app\common\controller\AuthAndBind;
use think\Controller;
use think\Db;
use alisms\SendSms;
use esign\EsignHandle;

/**
 * api
 */
class Shop extends AuthAndBind{
	
	public function __construct(){
		parent::__construct();
	}
	
	/**
	 * 获取商店发货类型列表
	 */
	public function getShopDeliveryTypeList(){
		if(request() -> isPost()){
			$in = input("post.");
			$bool = is_empty(['user_id', 'shop_id'], $in);
			if($bool){
				$outArr['code'] = '40004';
			}else{
				$userInfo = $this -> getUserInfo();
				
				$num = isset($in['num']) ? $in['num'] : 20;
				$start = isset($in['page']) && $in['page'] > 0 ? (($in['page'] - 1) * $num) : 0;
				
				$where[] = ['a.shop_id', 'eq', $in['shop_id']];
				$where[] = ['b.status', 'eq', 1];
				$field = ['a.*', 'b.name', 'b.rate', 'b.rate3'];
				$data = Db::table("gd_shop_delivery_type") -> alias('a') -> join('gd_delivery_type_config b', 'a.delivery_type_config_id = b.id')
															-> field($field) -> where($where) -> order("a.sort asc") -> limit($start, $num) -> select();
				$count = Db::table("gd_shop_delivery_type") -> alias('a') -> join('gd_delivery_type_config b', 'a.delivery_type_config_id = b.id')
															-> where($where) -> count();
				
				
				
				$outArr['code'] = '1';
				$outArr['info'] = $data;
				$outArr['totalNums'] = $count;
				
//				写入操作日志
				controller("service/OperLog") -> logs(
					[
						'title'=>'获取商店发货类型列表',
						'business_type'=>4,
						'oper_name'=>$userInfo['info']['nickname'],
						'oper_user_id'=>$userInfo['info']['id'],
						'json'=>[
							[
								'json_result'=>$outArr,
								'old_data'=> isset($old_data_json) ? $old_data_json : [],
							]
						]
					]
				);
			}
		}else{
			$outArr['code'] = '50001';
		}
		returnResults($outArr);
	}
	
	/**
	 * 批量设置商店发货类型
	 */
	public function batchSetShopDeliveryType(){
		if(request() -> isPost()){
			$in = input("post.");
			$bool = is_empty(['user_id', 'shop_id', 'delivery_type_config'], $in);
			if($bool){
				$outArr['code'] = '40004';
			}else{
				$userInfo = $this -> getUserInfo();
				
				$where[] = ['shop_id', 'in', $in['shop_id']];
				$oldData = Db::table("gd_shop_delivery_type") -> where($where) -> select();
				
				if( !empty($oldData) ){
					$delRes = Db::table("gd_shop_delivery_type") -> where($where) -> delete();
					if( !$delRes ) returnResults(['code'=>'-1', 'msg'=>'操作失败,请联系管理员']);
				}
				
				$newData = [];
				foreach ($in['shop_id'] as $k => $v) {
					foreach ($in['delivery_type_config'] as $kk => $vv) {
						$newData[] = [
							'delivery_type_config_id' => $vv['delivery_type_config_id'],
							'status' => $vv['status'],
							'shop_id' => $v,
							'sort' => $kk+1,
							'create_user_id' => $in['user_id'],
							'create_user_name' => $userInfo['info']['nickname'],
							'create_user_type' => $userInfo['info']['type'],
							'create_date' => date("Y-m-d H:i:s", time()),
						];
					}
				}
				
				$re = Db::table("gd_shop_delivery_type") -> insertAll($newData);
				if( !$re ) returnResults(['code'=>'-1', 'msg'=>'操作失败,请联系管理员']);
				
				
				$outArr['code'] = '1';
				
//				写入操作日志
				$old_data_json = $oldData;
				controller("service/OperLog") -> logs(
					[
						'title'=>'批量设置商店发货类型',
						'business_type'=>3,
						'oper_name'=>$userInfo['info']['nickname'],
						'oper_user_id'=>$userInfo['info']['id'],
						'json'=>[
							[
								'json_result'=>$outArr,
								'old_data'=> isset($old_data_json) ? $old_data_json : [],
							]
						]
					]
				);
			}
		}else{
			$outArr['code'] = '50001';
		}
		returnResults($outArr);
	}
	
	/**
	 * 获取指定商户待提现订单金额
	 */
    public function getOrderWaitingForWithdrawalTips(){
    	if(request() -> isPost()){
			$in = input("post.");
			$bool = is_empty(['user_id', 'shop_id'], $in);
			if($bool){
				$outArr['code'] = '40004';
			}else{
				
				$userInfo = $this -> getUserInfo();
				
				$shop = Db::table("gd_shop") -> where(['id'=>$in['shop_id']]) -> find();
				
				$where[] = ['shop_id', 'eq', $in['shop_id']];
				$where[] = ['status', 'eq', 1];
				$where[] = ['settle_status', 'eq', 0];
				$where[] = ['settle_status2', 'eq', 0];
				$data = Db::table("gd_order") -> where($where) -> sum("actual_price");
				
				$outArr['code'] = '1';
				$outArr['info'] = ($data > $shop['withdrawal_reminder_amount']) ? TRUE :FALSE;
				
//				写入操作日志
//				$old_data_json = $oldData;
				controller("service/OperLog") -> logs(
					[
						'title'=>'用户获取订单提示',
						'business_type'=>4,
						'oper_name'=>$userInfo['info']['nickname'],
						'oper_user_id'=>$userInfo['info']['id'],
						'json'=>[
							[
								'json_result'=>$outArr,
								'old_data'=> isset($old_data_json) ? $old_data_json : [],
							]
						]
					]
				);
			}
		}else{
			$outArr['code'] = '50001';
		}
		returnResults($outArr);
    }
	
	/**
	 * 批量审核店铺
	 */
	public function batchCheck(){
		if(request() -> isPost()){
			$in = input("post.");
			$bool = is_empty(['user_id', 'id', 'status'], $in);
			if($bool){
				$outArr['code'] = '40004';
			}else{
				$userInfo = $this -> getUserInfo();
				
				$where[] = ['id', 'in', $in['id']];
				$oldData = Db::table("gd_shop") -> where($where) -> select();
				if( empty($oldData) ) returnResults(['code'=>'-1', 'msg'=>'原数据有误']);
				
				if( !empty($oldData) ){
					Db::startTrans();
					foreach ($oldData as $k => $v) {
						$save['status'] = $in['status'];
						$save['verify_date'] = date("Y-m-d H:i:s", time());
						$save['verify_content'] = $in['verify_content'];
						$res = Db::table("gd_shop") -> where(['id'=>$v['id']]) -> update($save);
						if( !$res ) {
							Db::rollback();
							returnResults(['code'=>'-1', 'msg'=>'操作失败,请联系管理员']);
						}
						
						if( $in['status'] == 1 ){
//							变更用户类型
							$oldUser = Db::table("gd_user") -> where(['id'=>$v['create_user_id']]) -> find();
							if( $oldUser['type'] != 3 ){
								$re = Db::table("gd_user") -> where(['id'=>$v['create_user_id']]) -> update(['type'=>3]);
								if( !$re ) {
									Db::rollback();
									returnResults(['code'=>'-1', 'msg'=>'操作失败,请联系管理员']);
								}
						
//								绑定用户权限
								$newAuthGroupAccess = [];
								foreach ($in['authGroupAccess'] as $kk => $vv) {
									$newAuthGroupAccess[$kk]['uid'] = $v['create_user_id'];
									$newAuthGroupAccess[$kk]['group_id'] = $vv;
								}
								$res = Db::table("gd_auth_group_access") -> insertAll($newAuthGroupAccess);
								if( !$res ) {
									Db::rollback();
									returnResults(['code'=>'-1', 'msg'=>'操作失败,请联系管理员']);
								}
							}
						}
					}
					Db::commit();
				}
				
				$outArr['code'] = '1';
				
//				写入操作日志
				$old_data_json = $oldData;
				controller("service/OperLog") -> logs(
					[
						'title'=>'批量审核店铺',
						'business_type'=>3,
						'oper_name'=>$userInfo['info']['nickname'],
						'oper_user_id'=>$userInfo['info']['id'],
						'json'=>[
							[
								'json_result'=>$outArr,
								'old_data'=> isset($old_data_json) ? $old_data_json : [],
							]
						]
					]
				);
			}
		}else{
			$outArr['code'] = '50001';
		}
		returnResults($outArr);
	}
	
	/**
	 * 详情
	 */
	public function details(){
		if(request() -> isPost()){
			$in = input("post.");
			$bool = is_empty(['user_id'], $in);
			if($bool){
				$outArr['code'] = '40004';
			}else{
				$userInfo = $this -> getUserInfo();
				
				if( isset($in['id']) ) $where[] = ['id', 'eq', $in['id']];
				if( isset($in['create_user_id']) ) $where[] = ['create_user_id', 'eq', $in['create_user_id']];
				if( isset($in['status']) ) $where[] = ['status', 'eq', $in['status']];
				
				$data = Db::table("gd_shop") -> where($where) -> find();
				
				$outArr['code'] = '1';
				$outArr['info'] = $data;
				
//				写入操作日志
				controller("service/OperLog") -> logs(
					[
						'title'=>'获取店铺详情',
						'business_type'=>4,
						'oper_name'=>$userInfo['info']['nickname'],
						'oper_user_id'=>$userInfo['info']['id'],
						'json'=>[
							[
								'json_result'=>$outArr,
								'old_data'=> isset($old_data_json) ? $old_data_json : [],
							]
						]
					]
				);
			}
		}else{
			$outArr['code'] = '50001';
		}
		returnResults($outArr);
	}
	
	/**
	 * 列表
	 */
	public function index(){
		if(request() -> isPost()){
			$in = input("post.");
			$bool = is_empty(['user_id'], $in);
			if($bool){
				$outArr['code'] = '40004';
			}else{
				$userInfo = $this -> getUserInfo();
				
				$num = isset($in['num']) ? $in['num'] : 20;
				$start = isset($in['page']) && $in['page'] > 0 ? (($in['page'] - 1) * $num) : 0;
				
				$where = [];
//				$where[] = ['is_delete', 'eq', 0];
				if( isset($userInfo['auth_group']) && $userInfo['auth_group']['path'] == 'STORE' ) $where[] = ['id', 'eq', $userInfo['shop']['id']];						//商家
				if( isset($userInfo['auth_group']) && $userInfo['auth_group']['path'] == 'REGION' ) {																		//代理商													
					if( empty($userInfo['shop']) ) returnResults(['code'=>'99999']);
					$where[] = ['id', 'in', array_column($userInfo['shop'], 'id')];
				}
				if( isset($in['create_date']) ) $where[] = ['create_date', 'between', $in['create_date']];
				if( isset($in['verify_date']) ) $where[] = ['verify_date', 'between', $in['verify_date']];
				if( isset($in['create_user_id']) ) $where[] = ['create_user_id', 'eq', $in['create_user_id']];
				if( isset($in['status']) ) $where[] = ['status', 'eq', $in['status']];
				if( isset($in['state']) ) $where[] = ['state', 'eq', $in['state']];
				if( isset($in['shop_id']) ) $where[] = ['id', 'eq', $in['shop_id']];
				if( isset($in['name']) ) $where[] = ['name', 'like', '%'.trim($in['name']).'%'];
				if( isset($in['phone']) ) $where[] = ['phone', 'like', '%'.trim($in['phone']).'%'];
				
				if( isset($in['referrer_id']) && $in['referrer_id'] > 0 ){
					$userWhere = [];
					$userWhere[] = ['referrer_id', 'eq', $in['referrer_id']];
					$userWhere[] = ['type', 'eq', 3];
					$userType3 = Db::table("gd_user") -> field(['id']) -> where($userWhere) -> select();
					if( empty($userType3) ) returnResults(['code'=>'99999']);
					$where[] = ['create_user_id', 'in', array_column($userType3, 'id')];
				}
				
				$data = Db::table("gd_shop") -> where($where) -> order("id desc") -> limit($start, $num) -> select();
				$count = Db::table("gd_shop") -> where($where) -> count();
				
				if( !empty($data) ){
					foreach ($data as $k => $v) {
						$userData = Db::table("gd_user") -> where(['id'=>$v['create_user_id']]) -> find();
						$data[$k]['userPhone'] = $userData['phone'];
						$data[$k]['userName'] = $userData['nickname'];
						$data[$k]['avatar'] = $userData['avatar'];
						$data[$k]['nickname2'] = $userData['nickname2'];
						$data[$k]['referrer_id'] = $userData['referrer_id'];
					}
				}
				
				$outArr['code'] = '1';
				$outArr['info'] = $data;
				$outArr['totalNums'] = $count;				
				
//				写入操作日志
				controller("service/OperLog") -> logs(
					[
						'title'=>'获取店铺列表',
						'business_type'=>4,
						'oper_name'=>$userInfo['info']['nickname'],
						'oper_user_id'=>$userInfo['info']['id'],
						'json'=>[
							[
								'json_result'=>$outArr,
								'old_data'=> isset($old_data_json) ? $old_data_json : [],
							]
						]
					]
				);
			}
		}else{
			$outArr['code'] = '50001';
		}
		returnResults($outArr);
	}
	
	/**
	 * 编辑
	 */
	public function edit(){
		if(request() -> isPost()){
			$in = input("post.");
			$bool = is_empty(['user_id', 'id'], $in);
			if($bool){
				$outArr['code'] = '40004';
			}else{
				$userInfo = $this -> getUserInfo();
				
				$where[] = ['id', 'eq', $in['id']];
				$oldData = Db::table("gd_shop") -> where($where) -> find();
				if( empty($oldData) ) returnResults(['code'=>'-1', 'msg'=>'原数据有误']);
				
				$save = [];
				foreach ($in as $k => $v) {
					if( !in_array($k, ['id', 'user_id']) ){
						$save[$k] = is_array($v) ? json_encode($v, JSON_UNESCAPED_SLASHES) : $v;
					}
				}
				
				$save = filterArr($save, array_keys($save), $oldData);
				
				if( !empty($save) ){
					$re = Db::table("gd_shop") -> where($where) -> update($save);
					if( !$re ) returnResults2('-1', '编辑失败,请联系管理员');
				}
				$outArr['code'] = '1';
				
//				写入操作日志
				$old_data_json = $oldData;
				controller("service/OperLog") -> logs(
					[
						'title'=>'编辑店铺',
						'business_type'=>3,
						'oper_name'=>$userInfo['info']['nickname'],
						'oper_user_id'=>$userInfo['info']['id'],
						'json'=>[
							[
								'json_result'=>$outArr,
								'old_data'=> isset($old_data_json) ? $old_data_json : [],
							]
						]
					]
				);
			}
		}else{
			$outArr['code'] = '50001';
		}
		returnResults($outArr);
	}
	
	/**
	 * 新增
	 */
	public function add(){
		if(request() -> isPost()){
			$in = input("post.");
			$bool = is_empty(['user_id'], $in);
			if($bool){
				$outArr['code'] = '40004';
			}else{
				$userInfo = $this -> getUserInfo();
				
				$newData = [];
				foreach ($in as $k => $v) {
					if( !in_array($k, ['id', 'user_id']) ){
						$newData[$k] = is_array($v) ? json_encode($v, JSON_UNESCAPED_UNICODE) : $v;
					}
					$newData['create_user_id'] = $in['user_id'];
					$newData['create_user_name'] = $userInfo['info']['nickname'];
					$newData['create_user_type'] = $userInfo['info']['type'];
					$newData['create_date'] = date("Y-m-d H:i:s", time());
				}
				$re = Db::table("gd_shop") -> insertGetId($newData);
				if( !$re ) returnResults2('-1', '新增失败,请联系管理员');
				$outArr['code'] = '1';
				$outArr['info'] = $re;
				
//				写入操作日志
				controller("service/OperLog") -> logs(
					[
						'title'=>'新增店铺',
						'business_type'=>1,
						'oper_name'=>$userInfo['info']['nickname'],
						'oper_user_id'=>$userInfo['info']['id'],
						'json'=>[
							[
								'json_result'=>$outArr,
								'old_data'=> isset($old_data_json) ? $old_data_json : [],
							]
						]
					]
				);
			}
		}else{
			$outArr['code'] = '50001';
		}
		returnResults($outArr);
	}
	
}

?>